package pl.edu.agh.uddiProxy.server;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;

import pl.edu.agh.uddiProxy.client.Currency;

public class CurrencyConverter {
	private static Map<String, Currency> map;
	private static MessageFormat urlFormat = new MessageFormat("http://www.google.com/finance/converter?a={0}&to={1}&from={2}");
	
	public CurrencyConverter(String filename) throws FileNotFoundException {
		load(filename);
		System.out.println(filename + " " + new File(filename).getAbsolutePath());
	}
	
	private void load(String filename) throws FileNotFoundException {
		Scanner scanner = null;
		map = new HashMap<String, Currency>();
		try {
			scanner = new Scanner(new File(filename));
			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				String s[] = line.split(";");
				Currency currency = new Currency(s[0], s[1], s[2]);
				map.put(currency.getLocaleCode(), currency);
			}
		} finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}
	
	public Collection<Currency> getAllCurrency() {
		return map.values();
	}
	
	public Double convert(String currentCode, String targetCurrency, String value) throws IOException {
		if (currentCode.equalsIgnoreCase(targetCurrency)) {
			return new Double(value);
		}
		HttpClient httpClient = new HttpClient();
		HttpMethod method = new GetMethod(urlFormat.format(new String[] {value, targetCurrency, currentCode}));
		httpClient.executeMethod(method);
		if (method.getStatusCode() == HttpURLConnection.HTTP_OK) {
			return parseOutput(method.getResponseBodyAsString());
		} else {
			System.out.println(method.getStatusCode());
		}
		return null;
	}
	
	public static void main(String[] args) throws IOException {
		CurrencyConverter converter = new CurrencyConverter("currency.csv");
		System.out.println(converter.convert("FR", "PLN", "1"));
	}
	
	private Double parseOutput(String s) {
		if (s.contains("currency_converter_result")) {
			s = s.split("currency_converter_result")[1];
			s = s.split("<span")[1];
			s = s.split("/span")[0];
			s = s.split(">")[1];
			s = s.split("&")[0];
			return Double.parseDouble(s);
		}
		return null;
	}
}
